package com.ctgu.rabbitmq.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctgu.rabbitmq.entity.OrdersEntity;
import com.ctgu.rabbitmq.entity.UsersEntity;
import com.ctgu.rabbitmq.mapper.UsersMapper;
import com.ctgu.rabbitmq.service.UsersService;
import com.ctgu.rabbitmq.utils.ApiResult;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

/**
* @author Alex2
* @description 针对表【t_users】的数据库操作Service实现
* @createDate 2025-03-07 15:02:03
*/
@Log4j2
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, UsersEntity>
    implements UsersService {

    private static final String TAG = "Alex";

    /**
     * @ Author: Alex
     * @ Description: 实战案例-购物增加积分-插入用户
     */
    @Override
    public ApiResult insertUser(String username) {
        UsersEntity users = lambdaQuery().eq(UsersEntity::getUsername, username).one();
        if (users != null) {
            return ApiResult.error("该用户已存在");
        }
        UsersEntity usersEntity = new UsersEntity(null, username, null);
        boolean save = save(usersEntity);
        if (save) {
            return ApiResult.success("插入用户成功", usersEntity);
        } else {
            return ApiResult.error("插入用户失败");
        }
    }

    /**
     * @ Author: Alex
     * @ Description: 实战案例-购物增加积分-消费增加积分
     */
    @Override
    public void addRewardPoints(OrdersEntity ordersEntity) {
        boolean update = lambdaUpdate()
                .eq(UsersEntity::getId, ordersEntity.getUserId())
                .setSql("reward_points = COALESCE(reward_points, 0) + " + ordersEntity.getPrice())
                .update();
        if (update) {
            log.debug("{} : 增加积分成功 : {}", TAG, ordersEntity.getPrice().toString());
        } else {
            log.debug("{} : 增加积分失败，用户ID : {}", TAG, ordersEntity.getUserId());
        }
    }
}